package com.white.kotlindemo.widget

import kotlin.properties.Delegates

/**
 * Created by ytf on 2019/11/12.
 * Description: 偶数位是位置，奇数位是缩放比例
 */
class ScaleHelper(scales : FloatArray = floatArrayOf(0f,0f, 0.5f, 0.5f, 1f,0f)) {

    var mScales: FloatArray by Delegates.notNull()

    init {
        assertValues(scales)
    }

    private fun assertValues(scales: FloatArray) {
        if(scales.isEmpty()){
            mScales = floatArrayOf(1f, 0f, 1f, 1f)
            return
        }
        scales.forEach {
            require(it >= 0) { "Array value can not be negative!" }
        }

        require(!(scales.size < 2 || scales.size % 2 != 0)) { "Array length not match!" }

        mScales = scales
    }

    /**0  50%  100%</br>
     * 0, 0.5,  1</br>
     * fraction = 0.75   scale =
     */
    public fun getScale(fraction : Float) : Float{
        var minScale = 0f
        var maxScale = 0f
        var minScaleFraction = 0f
        var maxScaleFraction = 0f
        var scalePosition = 0f
        for (i in mScales.indices step 2){
            scalePosition = mScales[i]
            if(scalePosition <= fraction){
                minScale = mScales[i+1]
                minScaleFraction = mScales[i]
            }else{
                break
            }
        }
        for(i in mScales.size-1 downTo 0 step 2){
            scalePosition = mScales[i-1]
            if(scalePosition >= fraction){
                maxScale = mScales[i]
                maxScaleFraction = mScales[i-1]
            }else {
                break
            }
        }
        val ref = (fraction - minScaleFraction) / (maxScaleFraction - minScaleFraction)
        val result = (maxScale - minScale) * ref + minScale
        return if(isFinite(result)) result else minScale
    }

    private fun isFinite(value: Float): Boolean {
        return !java.lang.Float.isNaN(value) && !java.lang.Float.isInfinite(value)
    }
}

fun main(args: Array<String>) {
    println(ScaleHelper().getScale(0.75f))
}